class Tools {
  // 从cookie获取token的方法
  getTokenFromCookie() {
    const cookies = document.cookie.split(';')
    for (let cookie of cookies) {
      const [name, value] = cookie.trim().split('=')
      if (name === 'token') {
        return value
      }
    }
    return null
  }

  // 检查API响应状态，如果为false则跳转到登录页面
  checkAuthStatus(res, router, route) {
    if (res.data.status === false) {
      // 保存当前页面路径，用于登录后跳转回来
      const returnPath = route.path
      router.push({
        path: '/login',
        query: { returnUrl: returnPath }
      })
      return false // 返回false表示需要跳转登录
    }
    return true // 返回true表示认证正常
  }

  // 封装带认证检查的API调用
  async authApiCall(apiCall, router, route) {
    try {
      const res = await apiCall()
      const isAuthenticated = this.checkAuthStatus(res, router, route)
      return { res, isAuthenticated }
    } catch (error) {
      console.error('API调用失败:', error)
      throw error
    }
  }

  // RSA加密密码 rsaEncrypt
  async encryptPassword (publicKey, plaintext) {
    // 解析公钥
    const [nStr, eStr] = publicKey.split(',');
    const n = BigInt(nStr);
    const e = BigInt(eStr);
    
    // 模幂运算函数 (base^exponent mod modulus)
    function modPow(base, exponent, modulus) {
        if (modulus === 1n) return 0n;
        
        let result = 1n;
        base = base % modulus;
        
        while (exponent > 0n) {
            if (exponent % 2n === 1n) {
                result = (result * base) % modulus;
            }
            exponent = exponent >> 1n;
            base = (base * base) % modulus;
        }
        
        return result;
    }
    
    // 字符串转UTF-8字节数组
    function stringToUtf8Bytes(str) {
        if (typeof TextEncoder !== 'undefined') {
            // 浏览器环境
            const utf8Encoder = new TextEncoder();
            return utf8Encoder.encode(str);
        } else {
            // Node.js环境
            return Buffer.from(str, 'utf8');
        }
    }
    
    // 字节数组转大整数
    function bytesToBigInt(bytes) {
        let result = 0n;
        for (let i = 0; i < bytes.length; i++) {
            result = (result << 8n) | BigInt(bytes[i]);
        }
        return result;
    }
    
    try {
        // 将字符串转换为字节数组，然后转换为大整数
        const plaintextBytes = stringToUtf8Bytes(plaintext);
        const plaintextInt = bytesToBigInt(plaintextBytes);
        
        // 确保明文小于n
        if (plaintextInt >= n) {
            throw new Error("明文过长，请使用更长的密钥或分段加密");
        }
        
        // 加密：c = m^e mod n
        const ciphertextInt = modPow(plaintextInt, e, n);
        
        // 将整数转换为十六进制字符串
        return ciphertextInt.toString(16);
        
    } catch (error) {
        throw new Error(`RSA加密失败: ${error.message}`);
    }
  }
}

export const tools = new Tools()
